<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
use DateTime;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;

    public function __construct()
    {

    }
    protected function ajaxReturn($data)
    {
        $locale = request()->headers->all()['language'][0] ?? 'zh';
        $file = null;
        if (!empty($locale)) {
            // 定义 JSON 文件路径
            $jsonFile = '../lang/' . $locale . '.json';
            // 检查文件是否存在
            if (file_exists($jsonFile)) {
                // 读取文件内容
                $jsonContent = file_get_contents($jsonFile);
                // 检查是否读取成功
                if ($jsonContent !== false) {
                    // 将 JSON 转换为 PHP 数组（true 表示返回数组）
                    $file = json_decode($jsonContent, true);
                }
            }
        }
        $msgarr=explode('|',$data['msg']);
        $msgstr='';
        foreach ($msgarr as $key) {
            if(isset($file[$key])){
                $msgstr.=$file[$key].' ';
            }else{
                $msgstr.=$key.' ';
            }
        }
        //$data['locale'] = $locale;
        $data['msgbase'] = $data['msg'];
        $data['msg'] = trim($msgstr);
        return response()->json($data);
    }

    protected function decodetoken()
    {
        // 尝试从请求中获取用户
        $user = JWTAuth::parseToken()->authenticate();
        return $user;
    }

    protected function I($param)
    {
        // 判断是否是字符串
        if (is_string($param)) {
            // 如果是字符串，转换为小写
            $param = strtolower($param);
            if ($param == 'null' || $param == 'undefined') {
                return null;
            }
            return $param;
        } else {
            return $param;
        }
    }

    //返回日期差
    protected function getdatediff($begin, $end, $type = 'year')
    {
        if (empty($begin)) {
            return '';
        }
        $start = new DateTime($begin);
        $now = new DateTime($end); // 获取当前日期
        // 计算日期差异
        $interval = $start->diff($now);
        if ($type == 'year') {
            return $interval->y;
        }
    }
    //获取DB查询的SQL语句
    protected function getsql($query)
    {
        // 获取SQL语句和绑定参数
        $sql = $query->toSql();
        $bindings = $query->getBindings();

        // 自定义函数来替换绑定参数到SQL语句中
        function replaceBindingsInSql($sql, $bindings)
        {
            foreach ($bindings as $key => $value) {
                if (is_string($value)) {
                    $value = "'$value'"; // 对字符串类型的值添加单引号
                } elseif (is_null($value)) {
                    $value = 'NULL';
                }
                $sql = preg_replace('/\?/', $value, $sql, 1);
                $sql = str_replace('`', '', $sql);
            }
            return $sql;
        }
        return replaceBindingsInSql($sql, $bindings);
    }

    //操作日志
    protected function log($info)
    {
        try {
            if (empty($info['operator'])) {
                $usr = $this->decodetoken();
                $info['operator'] = $usr->name;
            }
            if (empty($info['from'])) {
                $info['from'] = 'web操作';
            }
            //记录登录日志
            $loglist = [];
            $loglist['operator'] = $info['operator'];
            $loglist['editdate'] = date('Y-m-d H:i:s');
            $loglist['type'] = $info['type'];
            $loglist['billcaption'] = $info['billcaption'];
            $loglist['des'] = $info['des'];
            $loglist['from'] = $info['from'];
            DB::table('UseLog')->insert($loglist);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => '日志保存失败：' . $e->getMessage()]);
        }
    }

    protected function domainurl($key)
    {
        if (empty($key)) {
            return '';
        }
        return env('APP_URL') . $key;
    }

    //删除文件
    protected function removefilebase($path)
    {

        $sart = strpos($path, 'uploads');
        $path = substr($path, $sart, 500);
        //路径为空直接返回
        if (empty($path)) {
            return true;
        }
        //文件不存在直接返回
        if (!file_exists($path)) {
            return true;
        }
        unlink($path); // 删除文件
        if (!file_exists($path)) {
            return false;
        } else {
            return true;
            ;
        }
    }

    //取redis缓存字符
    protected function Redisgetstring($rediskey)
    {
        $redisdata = Redis::get($rediskey);
        if ($redisdata) {
            return json_decode($redisdata, true);
        } else {
            return [];
        }
    }
    //设置redis缓存字符
    protected function RedisSetstring($rediskey, $data, $timeout = 43200)
    {
        Redis::set($rediskey, json_encode($data));
        //设置该键的过期时间为 12小时
        Redis::expire('key', $timeout);
    }
    //删除redis字符缓存
    protected function RedisDelstring($rediskey)
    {
        Redis::del($rediskey);
    }
}
